<?php


namespace app\common\library\dingding;


class AliDingDing {

    public $_postUrl = 'https://oapi.dingtalk.com/robot/send?access_token=07474c696896be29c0040c05ee863c2f39a1797ddf30be71cce1b8045968310f';

    public $_msgInfo;

    public $_userList = [];

    private $_allowMsgType = array('text','link','markdown');

    public function __construct ($access_token) {
        $this->_postUrl = 'https://oapi.dingtalk.com/robot/send?access_token=' . $access_token;
    }

    // 创建回复
    public function assign ($type='text',$content){
        if (in_array($type,$this->_allowMsgType)){
            $this->_msgInfo['msgtype'] = $type;
            switch ($type){
                case 'text':
                    $this->_msgInfo['text']['content'] = $content;
                    break;
                default:
                    break;
            }
            return $this;
        } else {
            die('非法类型');
        }
    }

    // At指定人
    public function at ($all=true,$limit=array()){
        if ($all===true){
            $this->_msgInfo['at']['atMobiles'] = $this->_userList;
            $this->_msgInfo['at']['isAtAll']   = true;
        }
        return $this;
    }

    // 发送请求
    public function send(){
        $sendStatus = $this->HttpPost($this->_msgInfo,$this->_postUrl);
        return $sendStatus;
    }

    //请求
    public function HttpPost($PostArry,$request_url){
        $postDataString = json_encode($PostArry);//格式化参数
        $content_type = array('Content-Type:application/json;charset=utf-8');
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $request_url); // 要访问的地址
        curl_setopt($curl, CURLOPT_HTTPHEADER, $content_type);
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postDataString); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环返回
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            $tmpInfo = curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo;   // 返回数据
    }
}